import qs from 'qs';
import { GetMenuBy } from "@/api/stu/bigdataprocessing"
import { LoadGetResource, UpdateResource, DeleteResource } from "@/api/admin/python"
import { type PaginationProps } from "@pureadmin/table";
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance, dayjs } from "element-plus";
export function useIndex() {
  // 获取题目列表
  const loadingfile = ref(false);
  const dataList = ref([]);
  const loading = ref(false);
  const VisibleTitle = ref("");
  const updatePanelVisible = ref(false);
  const isdisabled = ref<boolean>(false);
  const showfiles = reactive<any>({
    fileType: "",
    url: "",
    fileHost: ""//文件路径
  });
  const AstrictFileType = ref<string>(".pdf,image/jpg,image/jpeg,image/png,application/msword,text/html,video/mp4,application/pdf,application/vnd.openxmlforma,application/vnd.ms-excel,application/vnd.ms-powerpoint,xls,xlsx,ppt");
  // 搜索from 提交的内容
  const SubmitFrom = reactive<any>({
    moduleId: {},
    menuId: "",
    questionType: "",
    title: ""
  });

  // from 搜索表 下拉多选框的内容
  const ListFrom = reactive<any>({
    ModelList: [],
    ChildList: [],
    QuestionType: [
      { id: "1", title: "文档" },
      { id: "2", title: "课件" },
      { id: "3", title: "视频" },
      { id: "4", title: "其他" }
    ]
  })

  // 上传from表单中 选择框的内容
  const updateFrom = reactive<any>({
    ModelList: [],
    ChildList: [],
    QuestionType: [
      { id: "1", title: "文档" },
      { id: "2", title: "课件" },
      { id: "3", title: "视频" },
      { id: "4", title: "其他" }
    ]
  });

  // 添加or修改的内容
  const subupfrom = reactive<any>({
    resourceId: 0,
    createTime: "",
    moduleName: "",
    moduleId: {},
    menuName: "",
    menuId: "",
    resourcetype: "",
    isShow: true,
    resourceName: "",
    fileSize: "",
    uploadUser: "",
    fileType: "",
    resourceAbstract: "",
    url: []
  })

  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 列表头部
  const columns: TableColumnList =
    [{
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "模块名称",
      prop: "moduleName",
      minWidth: 100
    }, {
      label: "菜单名称",
      prop: "menuName",
      minWidth: 100
    }, {
      label: "类型",
      prop: "resourceType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.resourceType === 1 ? "warning" :
            row.resourceType === 2 ? "danger" :
              row.resourceType === 3 ? "success" : ""}>
          {
            row.resourceType === 1 ? "文档" :
              row.resourceType === 2 ? "课件" :
                row.resourceType === 3 ? "视频" : "其他"
          }
        </el-tag>
      )
    }, {
      label: "文件名称",
      prop: "resourceName",
      minWidth: 100
    }, {
      label: "文件类型",
      prop: "fileType",
      minWidth: 100
    }, {
      label: "文件大小(KB)",
      prop: "fileSize",
      minWidth: 100
    }, {
      label: "上传时间",
      prop: "createTime",
      minWidth: 100
    }, {
      label: "上传人",
      prop: "uploadUser",
      minWidth: 100
    }, {
      label: "是否展示",
      prop: "isShow",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={row.isShow ? "success" : "danger"}>
          {row.isShow ? "是" : "否"}
        </el-tag>
      )
    }, {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }]

  const rules = {
    moduleId: [{
      required: true,
      message: "请选择模块名称！",
      trigger: ["blur", "change"]
    }],
    menuId: [{
      required: true,
      message: "请选择菜单名称！",
      trigger: ["blur", "change"]
    }],
    isShow: [{
      required: true,
      message: "请选择是否展示资源！",
      trigger: ["blur", "change"]
    }],
    questionType: [{
      required: true,
      message: "请选择题目类型！",
      trigger: ["blur", "change"]
    }],
    resourceName: [{
      required: true,
      message: "请输入文件名称！",
      trigger: ["blur", "change"]
    }],
    url: [{
      required: true,
      message: "请上传100M以内的文件！",
      trigger: ["blur", "change"]
    }]
  }


  /***************************** 方法 **********************************/
  // 获取子菜单
  function GetModulChildrens(row: any) {
    SubmitFrom.menuId = ""
    ListFrom.ChildList = row.childrens;
  }

  // 获取模块名称 -- 菜单列表
  async function getModulName() {
    const menuid = qs.stringify({ moudleId: 687 });
    const respone = await GetMenuBy(menuid);
    ListFrom.ModelList = respone.data;
    updateFrom.ModelList = respone.data;
  }

  // 添加-修改
  function handleUpdate(row) {
    updatePanelVisible.value = true;
    if (row) {
      VisibleTitle.value = "修改";
      isdisabled.value = true;
      nextTick(() => {
        subupfrom.resourceId = row.resourceId;
        subupfrom.createTime = row.createTime;
        subupfrom.moduleName = row.moduleId;
        subupfrom.moduleId = row.moduleName;
        subupfrom.menuId = row.menuName;
        subupfrom.menuName = row.menuId;
        subupfrom.resourcetype = row.resourceType === 1 ? "文档" :
          row.resourceType === 2 ? "课件" :
            row.resourceType === 3 ? "视频" : "其他";
        subupfrom.isShow = row.isShow;
        subupfrom.resourceName = row.resourceName;
        subupfrom.resourceAbstract = row.resourceAbstract;
        subupfrom.url = row.url;
        subupfrom.fileSize = row.fileSize;
        subupfrom.fileType = row.fileType;
        subupfrom.uploadUser = row.uploadUser;
      })
      return
    }
    VisibleTitle.value = "添加"
    isdisabled.value = false;
  }

  // 删除
  async function handleDelete(row) {

    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      // 确定
      const resourceId = qs.stringify({ resourceId: row.resourceId })
      const respone = await DeleteResource(resourceId);
      if (respone.success) {
        ElMessage.success(respone.msg)
        SearchForm()
      } else {
        ElMessage.error(respone.msg)
      }
    }).catch(() => { })



  }

  // 搜索-获取资源列表
  async function SearchForm() {
    const res = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      moduleId: SubmitFrom.moduleId.id,
      menuId: SubmitFrom.menuId,
      resourceType: SubmitFrom.questionType,
      resourceName: SubmitFrom.title
    }
    const respone = await LoadGetResource(res);
    dataList.value = respone.data.list;
    pagination.total = respone.data.totalCount;
  }

  // 保存资源
  function SaveTopic(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      let res = {}
      if (subupfrom.resourceId) {
        // 修改
        res = {
          ...subupfrom, ...{
            menuId: subupfrom.menuName,
            menuName: subupfrom.menuId,
            moduleId: subupfrom.moduleName,
            moduleName: subupfrom.moduleId,
            resourcetype: subupfrom.resourcetype == "文档" ? '1' :
              subupfrom.resourcetype == "课件" ? '2' :
                subupfrom.resourcetype == "视频" ? '3' : "4"
          }
        }
      } else {
        // 添加
        res = {
          ...subupfrom, ...{
            menuId: subupfrom.menuId.id,
            menuName: subupfrom.menuId.displayName,
            moduleId: subupfrom.moduleId.id,
            moduleName: subupfrom.moduleId.displayName,
            uploadUser: JSON.parse(localStorage.getItem("user-info")).username,
            url: subupfrom.url[0].response.data.fileUrl
          }
        }
      }
      const respone = await UpdateResource(res);
      if (respone.success) {
        SearchForm();
        row.resetFields();
        updatePanelVisible.value = false;
        ElMessage.success(respone.msg);
        return
      }
      ElMessage.success(respone.msg);
    })
  }

  // 预览文件
  function showfile(row) {
    console.log("Loading", row)
    loadingfile.value = true;
    showfiles.fileType = row.fileType;
    showfiles.url = row.url;
    showfiles.fileHost = row.fileHost;//文件路径
  }

  // 关闭预览文件
  function HideFile() {
    loadingfile.value = false;
    showfiles.fileType = "";
    showfiles.url = "";
    showfiles.fileHost = "";//文件路径
  }

  // 上传文件时
  function handleBeforeUpload(file) {
    // console.log("before upload", file)
    if (file.size / 1024 / 1024 > 100) {
      ElMessage.warning("文件大小不能超过100M！");
      return false;
    }
    subupfrom.fileSize = file.size;
  }

  // 上传文件成功
  function handleSuccessUpload(file) {
    subupfrom.fileType = file.data.fileType
  }

  // 关闭
  function HideVisible(row: FormInstance | undefined) {
    subupfrom.resourceId = 0;
    row.resetFields();
    updatePanelVisible.value = false;
  }

  function GetModulChildrenss(row: any) {
    subupfrom.menuId = ""
    updateFrom.ChildList = row.childrens;
  }

  function handleSizeChange(val: number) {
    SearchForm()
  }

  function handleCurrentChange(val: number) {
    SearchForm()
  }

  function handleSelectionChange(val) {
    SearchForm()
  }

  onMounted(() => {
    getModulName()
    SearchForm()
  })

  return {
    rules,
    dataList,
    loading,
    ListFrom,
    showfiles,
    columns,
    pagination,
    SubmitFrom,
    VisibleTitle,
    isdisabled,
    updateFrom,
    subupfrom,
    loadingfile,
    AstrictFileType,
    updatePanelVisible,
    showfile,
    HideFile,
    SaveTopic,
    HideVisible,
    SearchForm,
    handleUpdate,
    handleDelete,
    handleBeforeUpload,
    handleSizeChange,
    GetModulChildrens,
    handleCurrentChange,
    handleSuccessUpload,
    GetModulChildrenss,
    handleSelectionChange
  }
}
